<?php
require_once('../includes/settings.php');
require_once('../includes/functions.php');
require_once('../includes/repository.php');
require_once('../includes/sql.php');
deny_get_request();
deny_anonymous();

function save_definition($word_id, $user_id, $definition, $insert_stmt, $update_stmt){
	if(Definition::is_exist($word_id,$user_id)){
		return Definition::update($word_id, $user_id, $definition, $update_stmt);
	}else{
		$id = Definition::create($word_id, $user_id, $definition, $insert_stmt);
		return $id>0;
	}
}


$user_id = intval(user_val('id'));
$insert_stmt = Repository::prepare($SQL['word_definitions']['insert']);
$update_stmt = Repository::prepare($SQL['word_definitions']['update']);

if(isset($_REQUEST['action'])){
	$action = strtolower($_REQUEST['action']);

	if($action=='edit'){
		$word_id=intval($_POST['word_id']);
		$definition = trim($_POST['definition']);
		$result=save_definition($word_id, $user_id, $definition, $insert_stmt, $update_stmt);
		Repository::commit();
		Repository::close();
		_jsonp($result);
		exit();
	}
}else{

	if(!isset($_POST['words'])){
		_jsonp(array("error"=>"Invalid Parameters"));
		exit();
	}
	$str=strtolower($_POST['words']);
	$words=json_decode($str);
	$insert_user_word_stmt = Repository::prepare($SQL['user_words']['insert']);
	$result = true;
	foreach ($words as $word => $definition) {
		$word=strip_quotes($word);
		$word_id = Word::get_id($word);
		if($word_id==0){
			$word_id = Word::create($word);
		}
		$result = save_definition($word_id, $user_id, $definition, $insert_stmt, $update_stmt);
		if(!$result){
			Repository::rollback();
			_jsonp(false);
			exit();
		}
		UserWord::create($user_id, $word_id, $insert_user_word_stmt);
	}
	Repository::commit();
	Repository::close();
	_jsonp(true);
}
?>